/**
 * 
 */
package util;

import image.Image;

/**
 * @author nquangtrung
 *
 */
public class ColorTransformer {
	public static final String TAG = "ColorTransformer";
	public int[][][] yccdownsample(int[][][] ycc, int width, int height) {
		int[][][] newycc = new int[3][width][height];
		for (int x = 0; x < width; x += 4) {
			for (int y = 0; y < height; y += 4) {
				int avgCb = 0;
				int avgCr = 0;
				for (int dx = 0; dx < 4; dx++) {
					for (int dy = 0; dy < 4; dy++) {
						avgCb += ycc[1][x+dx][y+dy];
						avgCr += ycc[2][x+dx][y+dy];
					}
				}
				avgCb = (int) Math.round(avgCb / 16.0);
				avgCr = (int) Math.round(avgCr / 16.0);
				for (int dx = 0; dx < 4; dx++) {
					for (int dy = 0; dy < 4; dy++) {
						newycc[1][x+dx][y+dy] = avgCb;
						newycc[2][x+dx][y+dy] = avgCr;
					}
				}
			}
		}
		
		newycc[0] = ycc[0];
		
		return newycc;
	}
	/**
	 * http://www.equasys.de/colorconversion.html
	 * RGB to YCbCr conversion for SDTV (and JFIF)
	 * @param image
	 * @return
	 */
	public int[][][] rgb2ycc(Image image) {
		int width = image.getWidth();
		int height = image.getHeight();
		int[][][] newimg = new int[3][width][height];
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				int r = image.getRed(x, y);
				int g = image.getGreen(x, y);
				int b = image.getBlue(x, y);
				// Y = (0.299 * R) + (0.587 * G) + (0.114 * B)
				newimg[0][x][y] = (int) Math.round(0.299 * r + 0.587 * g + 0.114 * b);
				// Cb = 128 - (0.168736 * R) - (0.331264 * G) + (0.5 * B)
				newimg[1][x][y] = (int) Math.round(128 - (0.168736 * r) - (0.331264 * g) + (0.5 * b));
				// Cr = 128 + (0.5 * R) - (0.418688 * G) - (0.081312 * B)
				newimg[2][x][y] = (int) Math.round(128 + (0.5 * r) - (0.418688 * g) - (0.081312 * b));
			}
		}
		return newimg;
	}
}
